<template>
  <div>
    <h1>留言板效果</h1>
    <div class="avatar">
      <h4>头像选择</h4>
      <div class="img">
        <!-- 试一试循环怎么写 -->
        <img
          @click="getImg('01.jpg')"
          :class="{ active: img == '01.jpg' }"
          src="01.jpg"
          alt=""
        />
        <img
          @click="getImg('02.jpg')"
          :class="{ active: img == '02.jpg' }"
          src="02.jpg"
          alt=""
        />
        <img
          @click="getImg('03.jpg')"
          :class="{ active: img == '03.jpg' }"
          src="03.jpg"
          alt=""
        />
        <img
          @click="getImg('04.jpg')"
          :class="{ active: img == '04.jpg' }"
          src="04.jpg"
          alt=""
        />
        <img
          @click="getImg('05.jpg')"
          :class="{ active: img == '05.jpg' }"
          src="05.jpg"
          alt=""
        />
      </div>
    </div>
    <h5>昵称</h5>
    <input type="text" v-model="name" />
    <h5>留言内容</h5>
    <textarea name="" id="" cols="30" rows="10" v-model="content"></textarea>
    <h6>字数限制{{ 200 - content.length }}/200</h6>
    <button @click="add">提交</button>

    <table>
      <thead>
        <tr>
          <th>头像</th>
          <th>昵称</th>
          <th>留言内容</th>
          <th>留言时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in list" :key="index">
          <td><img class="table-img" :src="item.img" alt="" /></td>
          <td>{{ item.name }}</td>
          <td>{{ item.content }}</td>
          <td>{{ item.time }}</td>
          <td><button @click="remove(index)">删除</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [],
      //留言的列表数据
      name: "",
      //昵称的v-model
      content: "",
      // 留言内容的v-model
      img: "",
      //图片
    };
  },
  methods: {
    getImg(val) {
      this.img = val;
    },
    //把选中的头像的路径存下来
    add() {
      this.list.push({
        name: this.name,
        content: this.content,
        img: this.img,
        time: new Date().toLocaleString(),
      });
      //添加数据
      this.name = "";
      this.content = "";
      this.img = "";
      //添加完成后清空
    },
    remove(index) {
      this.list.splice(index, 1);
    },
    //删除
  },
  watch: {
    content(newval) {
      if (newval.length >= 200) {
        alert("不能再输入了");
        this.content = newval.slice(0, 200);
        return false;
      }
    },
    //监听 输入的留言内容的变化
  },
};
</script>
<style lang="scss">
.avatar {
  display: flex;
  .img {
    // overflow: hidden;

    img {
      width: 40px;
      height: 40px;

      border-radius: 50%;
      margin: 10px;
    }
    .active {
      border: 2px solid red;
    }
  }
}
.table-img {
  width: 50px;
  height: 50px;
}
</style>
